package com.pope.framework.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerInterceptor;

import com.pope.framework.core.util.StringUtil;
import com.pope.framework.third.ThirdUtil;
import com.pope.framework.util.TokenContext;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class TokenFilter extends OncePerRequestFilter{
	
	@Autowired
	private ThirdUtil thirdUtil;
//
//	@Override
//	 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
//			throws Exception {
//		
//		
//		return true;
//	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String url=request.getRequestURI();
		log.info("============="+url);
		if(url.indexOf("swagger-resources")>=0
				||url.indexOf("webjars")>=0
				||url.indexOf("v2")>=0
				||url.indexOf("swagger-ui.html")>=0
				||url.indexOf("doc.html")>=0
				|| url.indexOf("actuator")>=0
				||url.indexOf("discover")>=0) {
			
		}else {
			String token=request.getParameter("token");
			String operaterid=request.getParameter("operaterid");
			String site=request.getParameter("site");
			String appid=request.getParameter("appid");
			if(StrUtil.isBlank(token)) {
				throw new ServletException("token不能为空"); 
			}
			if(StrUtil.isBlank(appid)) {
				throw new ServletException("appid不能为空"); 
			}
			if(StrUtil.isBlank(operaterid)) {
				throw new ServletException("操作用户operaterid不能为空！");
			}
			if(StrUtil.isBlank(site)) {
				throw new ServletException("租户site不能为空！");
			}
			
			TokenContext.putSite(StringUtil.toInt(site));
			TokenContext.putStaff(StringUtil.toInt(operaterid));
			TokenContext.putApp(StringUtil.toInt(appid));
			//检测token正确性质
			if(!thirdUtil.voliadeToken(token)) {
				throw new ServletException("抱歉，您无权限访问！");
			}
			//存储token
			TokenContext.putToken(token);
		}
		filterChain.doFilter(request, response);
		
	}
	
}
